package Classic150;

public class 生命游戏 {
    /*
        纯模拟
     */
    int n = 0;
    int m = 0;

    public void gameOfLife(int[][] board) {
        n = board.length;
        m = board[0].length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                int count = countLivingCell(board, i, j);
                if (board[i][j] == 0 && count == 3) board[i][j] = 2;
                else if (board[i][j] == 1 && (count < 3 || count > 4)) board[i][j] = 3;
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i][j] == 2) board[i][j] = 1;
                else if (board[i][j] == 3) board[i][j] = 0;
            }
        }
    }

    private int countLivingCell(int[][] board, int i, int j) {
        int count = 0;
        for (int p = i - 1; p <= i + 1; p++) {
            for (int q = j - 1; q <= j + 1; q++) {
                if (p < 0 || p >= n || q < 0 || q >= m) continue;
                if (board[p][q] == 1 || board[p][q] == 3) count++;
            }
        }
        return count;
    }
}
